﻿using BCDto.WeChatComponent.WeChatUser;
using BCDto.WxLogin.WebLogin;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace BCService.WeChatComponent.WeChatLoginService
{
    public class WeChatLoginService : IWeChatLoginService
    {
        private readonly IConfiguration configuration;
        public WeChatLoginService(IConfiguration configuration)
        {
            this.configuration = configuration;
        }

        public WxLoginWebAccessTokenDto GetAccessToken(string code,bool isSim)
        {
            string appid = isSim?configuration["WeChatSimService:AppId"]: configuration["WeChatWebsiteService:AppId"];
            string secret = isSim?configuration["WeChatSimService:AppSecret"]: configuration["WeChatWebsiteService:AppSecret"];
            string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, secret, code);
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentLength = 0;
            request.ContentType = "json";
            request.Timeout = 10000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            bool bResult = (response.StatusCode == HttpStatusCode.OK);
            if (!bResult)
            {
                throw new ArgumentException("获取微信AccessToken失败");
            }
            string jsonString = string.Empty;

            #region 读取response响应并更新数据库
            using (var responseStream = response.GetResponseStream())
            {
                if (responseStream != null)
                {
                    using (var reader = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        jsonString = reader.ReadToEnd();
                    }
                }
            }
            #endregion
            if (jsonString.IndexOf("errcode") > -1)
            {
                throw new ArgumentException("获取AccessToken失败!");
            }
            WxLoginWebAccessTokenDto accessToken = JsonConvert.DeserializeObject<WxLoginWebAccessTokenDto>(jsonString);
            WeChatUserInfoDto weChatUserInfoDto = this.GetUserInfo(accessToken.access_token, accessToken.unionid);
            accessToken.Nickname = weChatUserInfoDto.Nickname;
            accessToken.Headimgurl = weChatUserInfoDto.Headimgurl;
            return accessToken;
        }

        public WeChatUserInfoDto GetUserInfo(string accessToken,string unionId)
        {
            string url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}", accessToken, unionId);
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentLength = 0;
            request.ContentType = "json";
            request.Timeout = 10000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            bool bResult = (response.StatusCode == HttpStatusCode.OK);
            if (!bResult)
            {
                throw new ArgumentException("获取微信用户信息失败");
            }
            string jsonString = string.Empty;

            #region 读取response响应并更新数据库
            using (var responseStream = response.GetResponseStream())
            {
                if (responseStream != null)
                {
                    using (var reader = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        jsonString = reader.ReadToEnd();
                    }
                }
            }
            #endregion

            return JsonConvert.DeserializeObject<WeChatUserInfoDto>(jsonString);
        }
    }
}
